﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using MapGIS.GeoDataBase;
using MapGIS.GeoObjects.SpatialRef;
using MapGIS.GeoObjects.Geometry;

namespace Wcf_MapFrame
{   
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码和配置文件中的类名“MapFrameService”。
    public class MapFrameService : IMapFrameService
    {
        //<summary>
        //接收客户端流
        //</summary>
        //<typeparam name="T"></typeparam>
        //<param name="getStream"></param>
        //<returns></returns>
        private T GetStream<T>(Stream getStream)
        {
            object dui = new object();
            try
            {
                byte[] resultByte = new byte[1024];
                List<byte> buffer = new List<byte>();
                int sum = 0;
                while ((sum = getStream.Read(resultByte, 0, resultByte.Length)) > 0)
                {
                    foreach (var i in resultByte)
                    {
                        if (i != 0)
                        {
                            buffer.Add(i);
                        }
                    }
                    resultByte = new byte[1024];
                }
                string json = Encoding.UTF8.GetString(buffer.ToArray());
                JavaScriptSerializer jss = new JavaScriptSerializer();
                dui = jss.Deserialize<T>(json);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return (T)dui;
        }

        public string CreatMapFrame(Stream s)
        {
            MapFrameInfo info = GetStream<MapFrameInfo>(s);
            Rect range = new Rect();
            range.XMin = info.xmin;
            range.XMax = info.xmax;
            range.YMin = info.ymin;
            range.YMax = info.ymax;
            string rt = MapFrame.GetMapGrid(info.scale, range, info.srs, info.title);
            //string rt = MapFrame.GetMapFrame(info.scale, range, info.srs, info.title);
            return rt;
        }

        public string InputShpe(string url)
        {
            return InputShp.Shp2Json(url);
        }

        public string InputShpe_Bat(string[] urls)
        {
            string strRt = "{\"layer\":[";
            for (int i = 0; i < urls.Length; i++)
            {
                strRt += InputShp.Shp2Json(urls[i]);
                if (i != urls.Length - 1)
                    strRt += ",";
            }
            strRt += "]}";
            return strRt;
        }
    }
}
